package com.zjzhang.mqtt;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.SpannableString;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ContextActivity extends FragmentActivity implements OnClickListener {

	private static final String TAG = ContextActivity.class.getSimpleName();
	private static int CASE_CAMERA =1;
	private static int CASE_VIDEO =2;
	
    private String mRemotePhoneNumber="13611156505";
	private String mSelfPhoneNumber="13611156504";
	private Bitmap mRemoteImage=null;
	private Bitmap mSelfImage=null;
	
	private ListCursorAdapter adapter = null;
	
	private Button mBtnSend;
	private Button mBtnCamera;
	private EditText mEditTextContent;
	private String mLastID="0";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_context);
		if (getIntent().getStringExtra("REMOTEPHONE")!=null)
			mRemotePhoneNumber=getIntent().getStringExtra("REMOTEPHONE");
		SharedPreferences prefs = getSharedPreferences(PushService.TAG, MODE_PRIVATE);
		mSelfPhoneNumber= prefs.getString(PushService.PREF_PHONE_NUMBER, null);
		{
			Uri uriNumber2Contacts = Uri
					.parse("content://com.android.contacts/data/phones/filter/"
							+ mSelfPhoneNumber);
			Cursor cursorCantacts = getContentResolver().query(
					uriNumber2Contacts, null, null, null, null);
			if (cursorCantacts.getCount() > 0) {
				cursorCantacts.moveToFirst();
				Long contactID = cursorCantacts.getLong(cursorCantacts
						.getColumnIndex("contact_id"));
				Uri uri = ContentUris.withAppendedId(
						ContactsContract.Contacts.CONTENT_URI, contactID);
				InputStream input = ContactsContract.Contacts
						.openContactPhotoInputStream(getContentResolver(), uri);
				mSelfImage = BitmapFactory.decodeStream(input);
				;
			}
		}
		{

			Uri uriNumber2Contacts = Uri
					.parse("content://com.android.contacts/data/phones/filter/"
							+ mRemotePhoneNumber);
			Cursor cursorCantacts = getContentResolver().query(
					uriNumber2Contacts, null, null, null, null);
			if (cursorCantacts.getCount() > 0) {
				cursorCantacts.moveToFirst();
				Long contactID = cursorCantacts.getLong(cursorCantacts
						.getColumnIndex("contact_id"));
				Uri uri = ContentUris.withAppendedId(
						ContactsContract.Contacts.CONTENT_URI, contactID);
				InputStream input = ContactsContract.Contacts
						.openContactPhotoInputStream(getContentResolver(), uri);
				mRemoteImage = BitmapFactory.decodeStream(input);
				;
			}
		}
		Log.d(TAG, "start onCreate~~~");

		final Button backButton = ((Button) findViewById(R.id.btn_back));
		backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		final TextView title= (TextView) findViewById(R.id.title);
		title.setText(mRemotePhoneNumber);


		getContentResolver().registerContentObserver(ContextContentProvider.CONTENT_URI, true, cob);

		//mLastID=getLastIDByCount("5");
		initView();
		initLoader();
		setListViewAdapter();

	}
//	private String getLastIDByCount(String count,String lastID)
//	{
//		Cursor cursor =  getContentResolver().query(ContextContentProvider.CONTENT_URI, null, "topic= ? AND self=? AND remote=? AND _id<=?", 
//		        new String[] {PushService.MQTT_CLIENT_ID+"/chat/"+mSelfPhoneNumber,mSelfPhoneNumber,mRemotePhoneNumber,lastID}, "_id desc limit "+count);
//		if (cursor.moveToLast())
//		{
//			return cursor.getString(cursor.getColumnIndex("_id"));
//		}
//		return "0";
//	}
//	
//	private String getLastIDByCount(String count)
//	{
//		Cursor cursor =  getContentResolver().query(ContextContentProvider.CONTENT_URI, null, "topic= ? AND self=? AND remote=? ", 
//		        new String[] {PushService.MQTT_CLIENT_ID+"/chat/"+mSelfPhoneNumber,mSelfPhoneNumber,mRemotePhoneNumber}, "_id desc limit "+count);
//		
//		if (cursor.moveToLast())
//		{
//			return cursor.getString(cursor.getColumnIndex("_id"));
//		}
//		return "0";
//	}
	private void initLoader() {
		getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
			@Override
			public Loader<Cursor> onCreateLoader(int id, Bundle args) {
				Log.d(TAG, "on create loader");
				CursorLoader cursorLoader = new CursorLoader(ContextActivity.this,
						ContextContentProvider.CONTENT_URI, null,  "topic= ? AND self=? AND remote=? AND _id>=?", 
				        new String[] {PushService.MQTT_CLIENT_ID+"/chat/"+mSelfPhoneNumber,mSelfPhoneNumber,mRemotePhoneNumber,mLastID}, null);
				// cursorLoader.setUpdateThrottle(1000);
				return cursorLoader;
			}

			@Override
			public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
				Log.d(TAG, "on loader finished");
				adapter.swapCursor(cursor);
			}

			@Override
			public void onLoaderReset(Loader<Cursor> loader) {
				Log.d(TAG, "on loader reset");
				adapter.swapCursor(null);
			}
		});
	}
	private void setListViewAdapter() {
		ListView listView = (ListView) findViewById(R.id.messagelist);
		Cursor cursor =  getContentResolver().query(ContextContentProvider.CONTENT_URI, null, "topic= ? AND self=? AND remote=? AND _id>=?", 
		        new String[] {PushService.MQTT_CLIENT_ID+"/chat/"+mSelfPhoneNumber,mSelfPhoneNumber,mRemotePhoneNumber,mLastID}, null);
		adapter = new ListCursorAdapter(this, cursor, true);
		listView.setAdapter(adapter);

	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_send:{
			send();
			break;
		}
		case R.id.btn_camera:{
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
			startActivityForResult(intent, CASE_CAMERA);
			break;
		}
		}
		
	}
	
	@Override  
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if (resultCode == Activity.RESULT_OK) {
				if (requestCode == CASE_CAMERA) {
					Bundle extras = data.getExtras();
					Bitmap bitmap = (Bitmap) extras.get("data");
					Bitmap bm = (Bitmap) data.getExtras().get("data");
					boolean sdCardExit = Environment.getExternalStorageState().equals(
							android.os.Environment.MEDIA_MOUNTED);
					File myPictureDir = null;
					if (sdCardExit) {
						myPictureDir = new File(Environment.getExternalStorageDirectory()
								.getAbsolutePath() + "/custom_picture");

						if (!myPictureDir.exists()) {
							myPictureDir.mkdir();
						}
					} else {
						return;
					}
					try {
						File f = File.createTempFile("img", ".jpg", myPictureDir);
						BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
						String photoPath = f.getPath();
						bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
						bos.flush();
						bos.close();

					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (requestCode == CASE_VIDEO) {

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void send() {
		String msg = mEditTextContent.getText().toString();
		if (msg.length() > 0)
		{
			String msgid=UUIDUtils.compressedUuid();
			int result=-1;
			try {
				result=mService.pubmessage(PushService.MQTT_CLIENT_ID+"/chat/"+mRemotePhoneNumber,msgid+":"+mSelfPhoneNumber+":"+msg);
			} catch (RemoteException e) {
				Log.e(TAG,"连接错误",e);
			}
			mEditTextContent.setText("");
		
			ContentValues con = new ContentValues();

			con.put("msgid", msgid);
			con.put("topic", PushService.MQTT_CLIENT_ID+"/chat/"+mSelfPhoneNumber);
			con.put("remote", mRemotePhoneNumber);
			con.put("self", mSelfPhoneNumber);
			con.put("message",msg);
			con.put("isout",1);
			con.put("static",result);
			
			getContentResolver().insert(ContextContentProvider.CONTENT_URI, con);
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& ((FaceRelativeLayout) findViewById(R.id.FaceRelativeLayout))
						.hideFaceView()) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void initView() {
		mBtnSend = (Button) findViewById(R.id.btn_send);
		mBtnSend.setOnClickListener(this);
		mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
		mBtnCamera =  (Button) findViewById(R.id.btn_camera);
		mBtnCamera.setOnClickListener(this);
	}
	
	private class ListCursorAdapter extends CursorAdapter{
	    private Context ctx;
	    private LayoutInflater mInflater;

	    public ListCursorAdapter(Context context, Cursor c, boolean autoRequery) {
			super(context, c, autoRequery);
	        mInflater = LayoutInflater.from(context);
	        ctx = context;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return super.getView(position, convertView, parent);
		}

		@Override
		public int getItemViewType(int position) {
			Cursor cursor=getCursor();
			cursor.moveToPosition(position);
			return cursor.getInt(cursor.getColumnIndex("isout"));
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}
		class ViewHolder {  
	        TextView tv_message=null;
	        TextView tv_name=null;
	        ImageView iv_userhead=null;
	        ImageView iv_static=null;
	    }  
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			//Log.i(TAG,"newIVEW");
			ViewHolder holder=new ViewHolder();
			int isout=cursor.getInt(cursor.getColumnIndex("isout"));
			View convertView=null;
			if (isout>0)
			{
				convertView=mInflater.inflate(R.layout.chatting_item_msg_text_right,null);
				holder.tv_message = (TextView)convertView.findViewById(R.id.tv_chatcontent);
				holder.tv_name = (TextView)convertView.findViewById(R.id.tv_username);
				holder.iv_userhead=(ImageView)convertView.findViewById(R.id.iv_userhead);
				holder.iv_static=(ImageView)convertView.findViewById(R.id.iv_static);
			}else
			{
				convertView=mInflater.inflate(R.layout.chatting_item_msg_text_left,null);
				holder.tv_message = (TextView)convertView.findViewById(R.id.tv_chatcontent);
				holder.tv_name = (TextView)convertView.findViewById(R.id.tv_username);
				holder.iv_userhead=(ImageView)convertView.findViewById(R.id.iv_userhead);
			}

			convertView.setTag(holder);
			return convertView;
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) {	
			//Log.i(TAG,"bindView");
			String remote = cursor.getString(cursor.getColumnIndex("remote"));
			String message = cursor.getString(cursor.getColumnIndex("message"));
			String self = cursor.getString(cursor.getColumnIndex("self"));
			int isout=cursor.getInt(cursor.getColumnIndex("isout"));
			int nStatic=cursor.getInt(cursor.getColumnIndex("static"));
			SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(ctx, message);

			ViewHolder holder = (ViewHolder)view.getTag();
			if (isout>0)
			{
				holder.tv_message.setText(spannableString);
				holder.tv_name.setText(self);
				if (nStatic<0){
					holder.iv_static.setVisibility(View.VISIBLE);
					holder.iv_static.setImageResource(R.drawable.faile);
				}
				else if (nStatic==0){
					holder.iv_static.setVisibility(View.VISIBLE);
					holder.iv_static.setImageResource(R.drawable.sucess);
				}
				else{
					holder.iv_static.setVisibility(View.VISIBLE);
					holder.iv_static.setImageResource(R.drawable.d2);
				}

				if (mSelfImage!=null){
					 holder.iv_userhead.setImageBitmap(mSelfImage); 
				}else
					holder.iv_userhead.setImageResource(R.drawable.mini_avatar_shadow);  
			}else{
				holder.tv_message.setText(spannableString);
				holder.tv_name.setText(remote);
				if (mRemoteImage!=null){
					 holder.iv_userhead.setImageBitmap(mRemoteImage); 
				}else
					holder.iv_userhead.setImageResource(R.drawable.mini_avatar_shadow);  
			}

		}
		
	}


	
//    private String getDate() {
//        Calendar c = Calendar.getInstance();
//        String year = String.valueOf(c.get(Calendar.YEAR));
//        String month = String.valueOf(c.get(Calendar.MONTH));
//        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
//        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
//        String mins = String.valueOf(c.get(Calendar.MINUTE));
//        StringBuffer sbBuffer = new StringBuffer();
//        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); 
//         return sbBuffer.toString();
//    }


	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "start onStart~~~");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.d(TAG, "start onRestart~~~");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "start onResume~~~");
		Intent intent = new Intent(ContextActivity.this, PushService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "start onPause~~~");
		unbindService(mConnection);
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "start onStop~~~");
	}

	@Override
	protected void onDestroy() {
		getContentResolver().unregisterContentObserver(cob);
		Log.d(TAG, "start onDestroy~~~");
		super.onDestroy();

	}
	IMQTTServiceADIL mService;
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = IMQTTServiceADIL.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}
	};
	
	
	private ContentObserver cob = new ContentObserver(new Handler()) {
		@Override
		public boolean deliverSelfNotifications() {
			return super.deliverSelfNotifications();
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			Log.d(TAG, "ContentObserver onChange~~~");
//			Cursor cursor = getContentResolver().query(ContextContentProvider.CONTENT_URI, null, null, null,null);
//			if (cursor.moveToFirst()) {
//				do  {
//					int id = cursor.getInt(cursor.getColumnIndex("_id"));
//					String message = cursor.getString(cursor.getColumnIndex("message"));
//					//Log.i(TAG,"id:"+id+"  message:" + message);
//				} while (cursor.moveToNext());
//			} else {
//				//Log.i("TAG", "");
//			}
//			cursor.close();

		}

	};

	
}